<?php

namespace App\Console\Commands\Data;

use App\Kuafu\Shop\Model\AreaModel;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;

class AreaCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'area:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成省市区数据库信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $path = storage_path('area/meituan_area.json');
        if (!$this->laravel->files->exists($path)) {
            throw new \Exception($path . '路径文件不存在');
        }

        $content = $this->laravel->files->get($path);
        if (($contentArr = json_decode($content, true)) == false) {
            throw new \Exception('数据非json格式');
        }

        $time = time();
        foreach ($contentArr['data'] as $type => $data) {
            $this->output->writeln($type);
            foreach ($data as $row) {
                $this->output->writeln($row['chineseFullName']);
                AreaModel::query()->insert([
                    'areaId'      => $row['id'],
                    'areaPid'     => $row['parentId'],
                    'cnShortName' => $row['chineseName'],
                    'cnFullName'  => $row['chineseFullName'],
                    'level'       => $row['level'],
                    'adCode'      => $row['adCode'],
                    'createdAt'   => $time,
                ]);
            }
        }
        return Command::SUCCESS;
    }


}
